package com.example.xm.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.example.xm.Entity.Commodity;
import com.example.xm.Entity.Image;
import com.example.xm.Entity.Kg;
import com.example.xm.config.PageResult;
import com.example.xm.servive.CoyServive;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/C")
public class CoyController {
    @Autowired
    CoyServive coyServive;

    /**获取*/
    @PostMapping("/search")
    public List<Commodity> Mail(@RequestBody Commodity commodity){
        System.out.println(coyServive.getCoy(commodity));
        return coyServive.getCoy(commodity);
    }

    /**分页*/
    @GetMapping("/pager")
    public PageResult selectPager(@RequestParam(name = "pageNum",required = false,defaultValue = "1") int pageNum,
                                  @RequestParam(name = "pageSize",required = false,defaultValue = "5") int pageSize,
                                  @RequestParam(required = false,defaultValue = "")String id,
                                  @RequestParam(required = false,defaultValue = "")String name,
                                  @RequestParam(required = false,defaultValue = "")String price,
                                  @RequestParam(required = false,defaultValue = "")String kg,
                                  @RequestParam(required = false,defaultValue = "")String date,
                                  @RequestParam(required = false,defaultValue = "")String img1,
                                  @RequestParam(required = false,defaultValue = "")String img2,
                                  @RequestParam(required = false,defaultValue = "")String img3,
                                  @RequestParam(required = false,defaultValue = "")String img4,
                                  @RequestParam(required = false,defaultValue = "")String xx,
                                  @RequestParam(required = false,defaultValue = "")Integer num,
                                  @RequestParam(required = false,defaultValue = "")String kg_kg,
                                  @RequestParam(required = false,defaultValue = "")String image
    ){
        //获取所有学生信息
        Commodity c = new Commodity();
        c.setId(id);
        c.setName(name);
        c.setPrice(price);
        c.setImg1(img1);
        c.setImg2(img2);
        c.setImg3(img3);
        c.setImg4(img4);
        c.setKg(kg);
        c.setXx(xx);
        c.setNum(num);
        if(!date.equals("") && !date.equals("null")){
            c.setDate(DateUtil.parse(date,"yyyy-MM-dd"));
        }

        c.setK(new Kg());
        c.getK().setKg_kg(kg_kg);
        c.setImage(new Image());
        c.getImage().setId(image);
        return coyServive.selectPager(pageNum,pageSize,c);
    }

    /**删除*/
    @DeleteMapping("/{id}")
    public int del(@PathVariable String id){
        return coyServive.del(id);
    }

    /**根据id来获取商品信息*/
    @GetMapping("/{id}")
    public Commodity getCoyId(@PathVariable String id){
        System.out.println(coyServive.getCoyId(id));
        return coyServive.getCoyId(id);
    }

    @PostMapping("")
    public int Add(@RequestBody Commodity commodity){
        System.out.println("添加了：" + commodity);
        return coyServive.Add(commodity);
    }

    @PostMapping("/gwc")
    public int AddGwc(@RequestBody Commodity commodity){
        System.out.println("添加到购物车：" + commodity);
        return coyServive.AddGwc(commodity);
    }

    /**修改商品信息*/
    @PutMapping("")
    public int Update(@RequestBody Commodity commodity){
        System.out.println("修改了：" + commodity);
        return coyServive.Update(commodity);
    }


    //导入
    @PostMapping("/importExcel")
    public int importExcel(@RequestParam MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<List<Object>> list = reader.read();
        //30	巴卡尔键鼠套装	111	101	2023/11/3	巴卡尔主题系列周边全新上线！套装内含：键盘*1、鼠标*1、鼠标垫*1；购买即可领取焚烬龙焰光环礼盒*1。	19	16.jpg	101

        int count =0;
        for(List<Object> obj:list){
            //创建出生日期对象
            Date date = DateUtil.parse(obj.get(4)+"","yyyy-MM-dd");//日期转字符串
            Integer num = Integer.valueOf(String.valueOf(obj.get(8)+""));//Integer转字符串
            //BigDecimal price = BigDecimal.valueOf(Long.parseLong(obj.get(3)+""));//BigDecimal转字符串
            Commodity c = new Commodity(obj.get(0)+"",obj.get(1)+"",obj.get(2)+"",obj.get(3)+"",date,obj.get(5)+"",obj.get(7)+"",num,obj.get(8)+"",obj.get(9)+"",obj.get(10)+"",null,null,null,null);
            count+=coyServive.Add(c);
        }
        System.out.println(list);
        return count;
    }

    //导出
    @GetMapping("/exportExcel")
    public void exportExcel(@RequestParam(required = false,defaultValue = "")String id,
                            @RequestParam(required = false,defaultValue = "")String name,
                            @RequestParam(required = false,defaultValue = "")String price,
                            @RequestParam(required = false,defaultValue = "")String date,
                            @RequestParam(required = false,defaultValue = "")String xx,
                            @RequestParam(required = false,defaultValue = "")String img1,
                            @RequestParam(required = false,defaultValue = "")Integer num,
                            @RequestParam(required = false,defaultValue = "")String kg_kg,
                            HttpServletRequest request, HttpServletResponse response) throws IOException {
        //Excel写入
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //定义单元格背景色
        StyleSet style = writer.getStyleSet();
        //设置字体
        Font font = writer.createFont();
        font.setBold(true);//加粗
        font.setColor(Font.COLOR_NORMAL);//字体颜色
        font.setItalic(true);//斜体

        //获取对象自定义种类样式
        //CellStyle cellStyle = style.getHeadCellStyle();//头部

        //第二个参数表示是否也设置头部单元格背景色
        style.setBackgroundColor(IndexedColors.LAVENDER,false);
        //字体颜色
        writer.getStyleSet().setFont(font,true);

        //获取所有学生信息
        Commodity c = new Commodity();
        c.setId(id);
        c.setName(name);
        c.setPrice(price);
        c.setImg1(img1);
        c.setXx(xx);
        c.setNum(num);
        if(!date.equals("") && !date.equals("null")){
            c.setDate(DateUtil.parse(date,"yyyy-MM-dd"));
        }

        c.setK(new Kg());
        c.getK().setKg_kg(kg_kg);
        List<Commodity> allStudents = coyServive.getCoy(c);
        writer.addHeaderAlias("id","编号");
        writer.addHeaderAlias("name","商品名");
        writer.addHeaderAlias("price","价格");
        writer.addHeaderAlias("img","图片");
        writer.addHeaderAlias("xx","商品详情");
        writer.addHeaderAlias("date","生产生日");
        writer.addHeaderAlias("kg_kg","重量");
        //默认的，未添加alias的属性也会写出，如果想只写出加了别名的字段，可以调用此方法排除之
        writer.setOnlyAlias(true);
        //合并单元格后的标题提行，使用默认标题样式
        writer.merge(5,"商品信息列表");

        //List<Object> row = ListUtil.of((CellSetter) cell -> cell.setCellValue("自定义内容"));//自定义导出内容
        //写入
        writer.write(allStudents,true);

        //当前响应对象输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //设置Http响应的内容为Excel类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        //添加附件，指定文件名
        response.setHeader("Content-Disposition","attachment;filename=" + UUID.randomUUID() +".xlsx");

        //将Excel输出到响应流中
        writer.flush(outputStream,true);

        //writer.writeRow(row);

        //关闭
        writer.close();
        IoUtil.close(outputStream);
    }
}
